package com.syni.mdd.yhd.common.all.listen.order;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.yhd.common.all.config.common.CommonSetUtils;
import com.syni.mdd.yhd.common.all.constants.AuroraPushCode;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.groupBuy.BmsUserBargain;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.activity.BmsBackCardService;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrLogicService;
import com.syni.mdd.yhd.common.all.service.activity.BmsDrOrderLogService;
import com.syni.mdd.yhd.common.all.service.groupBuy.BmsUserBargainService;
import com.syni.mdd.yhd.common.all.utils.SmsUtils;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.TokenManager;
import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDistSys.OrderSubmitDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddDistSys.FxCenterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @className OrderListener
 * @description TOO
 * @Author cfx
 * @DATE 2019/8/8 15:46
 * @VERSION 1.0
 **/
@Component
public class OrderPayListener implements ApplicationListener<OrderEvent> {
    private final static String MODEL = "orderPay";
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    BmsDxNewsService bmsDxNewsService;

    @Autowired
    BmsUserVideoDkService bmsUserVideoDkService;

    @Autowired
    BmsCommonService bmsCommonService;

    @Autowired
    BmsDxCouponService bmsDxCouponService;

    @Autowired
    BmsBackCardService bmsBackCardService;

    @Autowired
    BmsDrLogicService bmsDrLogicService;

    @Autowired
    BmsDxOrderService bmsDxOrderService;

    @Autowired
    BmsDrOrderLogService bmsDrOrderLogService;

    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsUserBargainService bmsUserBargainService;

    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;

    @Autowired
    FxCenterService fxCenterService;

    @Async
    public void onApplicationEvent(OrderEvent orderEvent) {
        String model = orderEvent.getSource().toString();
        if(!MODEL.equals(model)){
            return;
        }
        log.info("........................订单监听.......................");
        BmsDxOrder bmsDxOrder = orderEvent.getBmsDxOrder();
        BmsDxNews bmsDxNews = new BmsDxNews();
        bmsDxNews.setIsDelete(Constants.COMMON_FLAG_FALSE_INT);
        userDkBusiness(bmsDxOrder);
        if(bmsDxOrder.getOrderType() == Constants.ONLINE_ORDER_TYPE ||
                bmsDxOrder.getOrderType() == Constants.COUPONS_ORDER_TYPE){
            //统计销售量
            Integer couponId = bmsDxOrder.getBmsCouponId();
            if(bmsDxOrder.getOrderType() == Constants.ONLINE_ORDER_TYPE){
                //查询线上买单id
                List<BmsDxCoupon> bmsDxCouponList = bmsDxCouponService.getBaseDao().findByBmsBusinessIdAndType(bmsDxOrder.getBmsBusinessId(),Constants.ONLINE_ORDER_TYPE);
                if(bmsDxCouponList.size() > 0){
                    BmsDxCoupon bmsDxCoupon = bmsDxCouponList.get(0);
                    couponId = bmsDxCoupon.getId();
                }
            }
            redisTemplate.opsForZSet().incrementScore(Constants.REDIS_KEY_ORDER_SELL_NUM,"cp:" + couponId,1);
            //发送给商家
            bmsDxNews.setBmsBusinessId(bmsDxOrder.getBmsBusinessId());
            bmsDxNews.setOpUserId(bmsDxOrder.getBmsUserId());
            bmsDxNews.setBmsOrderId(bmsDxOrder.getId());
            bmsDxNews.setParentType(Constants.PARENTTYPT_CON);
            bmsDxNews.setChildType(Constants.PARENTTYPT_CON_BUSINESS_PAY);
            BmsUser bmsUser = TokenManager.getUser(bmsDxOrder.getBmsUserId());
            if(bmsUser != null) {
                bmsDxNews.setTitile(bmsUser.getLoginName());
            }
            bmsDxNews.setContent(bmsDxOrder.getActualConsum().toString());
            //bmsDxNews.setFromOrigin(Constants.BUSINESS_CLIENT);
            bmsDxNews.setOriginRole(Constants.BUSINESS_ROLE_ID);
            bmsDxNewsService.save(bmsDxNews);
            String alert = String.format(AuroraPushCode.pushTemplateMap.get(AuroraPushCode.BUSINESS_RECE_PAY).getAlert(),bmsDxNews.getTitile(),bmsDxNews.getContent());
            BmsCommonService.pushToFront(bmsDxNews,AuroraPushCode.BUSINESS_RECE_PAY,alert);
            //发送给用户
            BmsDxNews userNew = new BmsDxNews();
            BeanUtils.copyProperties(bmsDxNews,userNew);
            userNew.setId(null);
            userNew.setBmsUserId(bmsDxOrder.getBmsUserId());
            userNew.setParentType(Constants.PARENTTYPT_CON);
            userNew.setChildType(Constants.PARENTTYPT_CON_COUPON);
            userNew.setTitile(bmsDxOrder.getVendorName());
            //userNew.setFromOrigin(Constants.USER_CLIENT);
            userNew.setOriginRole(Constants.GENERAL_USER_ROLE_ID);
            bmsDxNewsService.save(userNew);
            alert = String.format(AuroraPushCode.pushTemplateMap.get(AuroraPushCode.USER_PAY).getAlert(),userNew.getTitile(),userNew.getContent());
            BmsCommonService.pushToFront(userNew,AuroraPushCode.USER_PAY,alert);
            //统计返现次数（返现卡活动）
            bmsDrOrderLogService.countBackCard(bmsDxOrder,null,bmsDxOrder.getActualConsum());
        }else if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_ORDER_TYPE){
            //统计团购订单销售量
            redisTemplate.opsForZSet().incrementScore(Constants.REDIS_KEY_ORDER_SELL_NUM,"gb:" + bmsDxOrder.getBmsGroupBuyId(),bmsDxOrder.getGroupBuyNum());
            //发送给用户（提示购买）
            bmsDxNews.setBmsUserId(bmsDxOrder.getBmsUserId());
            bmsDxNews.setBmsBusinessId(bmsDxOrder.getBmsBusinessId());
            bmsDxNews.setOpUserId(bmsDxOrder.getBmsUserId());
            bmsDxNews.setBmsOrderId(bmsDxOrder.getId());
            bmsDxNews.setParentType(Constants.PARENTTYPT_CON);
            bmsDxNews.setChildType(Constants.PARENTTYPT_CON_GROUP_BUY);
            bmsDxNews.setTitile(bmsDxOrder.getVendorName());
            Map<String,Object> userDataMap = new HashMap<>();
            userDataMap.put("groupName",bmsDxOrder.getBmsDxGroupBuy().getGroupName());
            userDataMap.put("groupBuyNum",bmsDxOrder.getGroupBuyNum());
            bmsDxNews.setContent(JSON.toJSONString(userDataMap));
            //bmsDxNews.setFromOrigin(Constants.USER_CLIENT);
            bmsDxNews.setOriginRole(Constants.GENERAL_USER_ROLE_ID);
            bmsDxNewsService.save(bmsDxNews);
            //进行极光推送
            String alert = String.format(AuroraPushCode.pushTemplateMap.get(AuroraPushCode.USER_PAY_GROUP_BUY).getAlert(),
                    bmsDxOrder.getGroupBuyNum(),bmsDxOrder.getVendorName(),bmsDxOrder.getBmsDxGroupBuy().getGroupName());
            BmsCommonService.pushToFront(bmsDxNews,AuroraPushCode.USER_PAY_GROUP_BUY,alert);
            //发送短信
            sendGroupBuySms(bmsDxOrder);
            //如果是特特乐团购，也算活动的一笔
            if(bmsDxOrder.getBmsDxGroupBuy() != null){
                BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
                if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                    List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findByOrderId(bmsDxOrder.getId());
                    if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0) {
                        bmsDxGroupBuyUseService.countBackCard(bmsDxGroupBuyUses.get(0));
                    }
                }
            }

        }else if(bmsDxOrder.getOrderType() == Constants.GROUP_BUY_BARGAIN_ORDER_TYPE){
            //发送短信
            sendGroupBuySms(bmsDxOrder);
            //统计砍价订单销售量
            redisTemplate.opsForZSet().incrementScore(Constants.REDIS_KEY_ORDER_SELL_NUM,"gb:" + bmsDxOrder.getBmsGroupBuyId(),bmsDxOrder.getGroupBuyNum());
            //如果是砍价团购
            if(bmsDxOrder.getBargainId() != null) {
                BmsUserBargain bmsUserBargain = bmsUserBargainService.getBargainById(bmsDxOrder.getBargainId());
                if (bmsUserBargain != null) {
                    bmsUserBargain.setStatus(BmsUserBargainService.PAY_STATUS);
                    bmsUserBargain.setOrderId(bmsDxOrder.getId());
                    bmsUserBargainService.getBaseDao().save(bmsUserBargain);
                }
                //调用saas支付接口
                bmsUserBargainService.orderPay(bmsUserBargain.getSaasOrderId());
                //分配给用户用户的返现卡金额
                bmsUserBargainService.handleBackCardLogic(bmsUserBargain);
           }
        }else if(bmsDxOrder.getOrderType() == Constants.FX_ORDER_TYPE){
            //TODO 处理分销的逻辑
            orderFxLogic(bmsDxOrder);
        }
    }


    /**
     * 处理分销订单逻辑
     * @param bmsDxOrder
     */
    public void orderFxLogic(BmsDxOrder bmsDxOrder){

        Integer userId = bmsDxOrder.getBmsUserId();
        OrderSubmitDto orderSubmitDto = new OrderSubmitDto();
        Integer shareId = bmsDxOrder.getShareId();
        Integer buyRole = fxCenterService.getFxRole(userId);
        orderSubmitDto.setBuyId(userId);
        orderSubmitDto.setBuyRole(buyRole);
        orderSubmitDto.setOrderId(bmsDxOrder.getId());
        orderSubmitDto.setAcrossCommision(bmsDxOrder.getBmsDxGroupBuy().getAcrossCommision());
        orderSubmitDto.setCommision(bmsDxOrder.getBmsDxGroupBuy().getCommision());
        orderSubmitDto.setGroupBuyNum(bmsDxOrder.getGroupBuyNum());
        orderSubmitDto.setIsBusinessConsume(bmsDxOrder.getBmsDxGroupBuy().getIsBusinessConsume());
        if(shareId != null){
            //分享链接
            Integer shareRole = fxCenterService.getFxRole(shareId);
            orderSubmitDto.setShareId(shareId);
            orderSubmitDto.setShareRole(shareRole);
        }
        Map<String, Object> submitMap = fxCenterService.orderSubmit(orderSubmitDto);
        if(submitMap.get("status").equals("00")){
            Map<String,Object> dataMap = (Map)submitMap.get("data");
            Double totalComm = Double.parseDouble(String.valueOf(dataMap.get("totalComm")));
            bmsDxOrder.setTotalComm(totalComm);
            bmsDxOrderService.save(bmsDxOrder);
        }
    }


    /**
     * @Description 打卡该商家
     * @Author: cfx
     * @Date: 2019/9/29
     */
    public void userDkBusiness(BmsDxOrder bmsDxOrder){
        try {
            //将该用户打卡该商家
            BmsUserVideoDk bmsUserVideoDk = bmsUserVideoDkService.getBaseDao().findByBmsUserIdAndBmsBusinessId(bmsDxOrder.getBmsUserId(),bmsDxOrder.getBmsBusinessId());
            if(bmsUserVideoDk == null){
                bmsUserVideoDk = new BmsUserVideoDk();
                bmsUserVideoDk.setBmsUserId(bmsDxOrder.getBmsUserId());
                bmsUserVideoDk.setBmsBusinessId(bmsDxOrder.getBmsBusinessId());
                bmsUserVideoDk.setDkTime(new Date());
                bmsUserVideoDkService.save(bmsUserVideoDk);
                bmsUserVideoDkService.addUserDkToRedis(bmsUserVideoDk.getBmsBusinessId(),1);
            }
        }catch (Exception e){
            log.error("userDkBusiness error ",e);
        }

    }

    /**
     * @Description 发送购买短信
     * @Author: cfx
     * @Date: 2019/8/28
     */
    public void sendGroupBuySms(BmsDxOrder bmsDxOrder){
        String templateIds = "groupBuy.templateId";
        BmsUser bmsUser = TokenManager.getUser(bmsDxOrder.getBmsUserId());
        if(bmsUser != null && StringUtils.isNotBlank(bmsUser.getPhone())){
            String phone = bmsUser.getPhone();
            BmsDxGroupBuy bmsDxGroupBuy = bmsDxOrder.getBmsDxGroupBuy();
            if(bmsDxGroupBuy != null) {
                if(bmsDxGroupBuy.getExpireTime() == null){
                    bmsDxGroupBuy.setExpireTime(bmsDxGroupBuy.getLimitBuyTime());
                }
                String[] params = {
                        bmsDxOrder.getGroupBuyNum().toString(),
                        bmsDxOrder.getVendorName(),
                        bmsDxOrder.getBmsDxGroupBuy().getGroupName(),
                        DateTimeUtils.converDateToString(bmsDxOrder.getBmsDxGroupBuy().getExpireTime(), DateTimeUtils.DATE_PATTERN_DAY_05),
                        };
                if(bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE){
                    templateIds = "groupBuy.tetele.templateId";
                    String title = String.format("%s张%s-%s",bmsDxOrder.getGroupBuyNum(),bmsDxOrder.getVendorName(),bmsDxGroupBuy.getGroupName());
                    //查询一下生成的券码
                    Map<String,Object> conditionMap = new HashMap<>();
                    conditionMap.put("orderId",bmsDxOrder.getId());
                    conditionMap.put("userId",bmsDxOrder.getBmsUserId());
                    conditionMap.put("status",Constants.GROUP_ALREADY_USE);
                    List<BmsDxGroupBuyUse> bmsDxGroupBuyUses = bmsDxGroupBuyUseService.getBaseDao().findAll(new SpecificationUtils(conditionMap));
                    List<String> codes = new ArrayList<>();
                    if(bmsDxGroupBuyUses != null && bmsDxGroupBuyUses.size() > 0){
                        for(BmsDxGroupBuyUse bmsDxGroupBuyUse : bmsDxGroupBuyUses){
                            codes.add(bmsDxGroupBuyUse.getGroupBuyCode());
                        }
                    }
                    String desc = CommonSetUtils.teteGroupBuyTemplates.get(0).getMsg();
                    String codesDesc = StringUtils.join(codes,"/");
                    if(CommonSetUtils.teteGroupBuyTemplates.containsKey(bmsDxGroupBuy.getId())){
                        desc = CommonSetUtils.teteGroupBuyTemplates.get(bmsDxGroupBuy.getId()).getMsg();
                    }
                    String sendDesc = String.format(desc,codesDesc);
                    /*String[] paramsSpe = {title,
                            DateTimeUtils.converDateToString(bmsDxGroupBuy.getUseStartTime(), DateTimeUtils.DATE_PATTERN_DAY_05),
                            DateTimeUtils.converDateToString(bmsDxGroupBuy.getUseEndTime(), DateTimeUtils.DATE_PATTERN_DAY_05),
                    codesDesc};*/
                    String[] paramsSpe = {title,
                            sendDesc,
                            DateTimeUtils.converDateToString(bmsDxGroupBuy.getUseEndTime(), DateTimeUtils.DATE_PATTERN_DAY_05)};
                    params = paramsSpe;
                }
                if(BmsCommonService.checkRunProfile(BmsCommonService.RUN_PRO)){
                    SmsUtils.send(phone,templateIds,params);
                }
            }
        }
    }
}
